import requests
from urllib.parse import urlparse, unquote
from api.encryption.url_algorithm import encodeUrl, encodeMd5, decodeUrl
from api.encryption.lc import lc

USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36"


def find_string_val(htmlContent, valueName, tag='"'):
    index = 0
    for key in [valueName, tag]:
        if index > -1:
            index = htmlContent.find(key, index)
    if index > -1:
        index += 1
        return htmlContent[index: htmlContent.find(tag, index)]
    return None


def find_int_val(htmlContent, valueName):
    index = 0
    for key in [valueName, '=']:
        if index > -1:
            index = htmlContent.find(key, index)
    if index > -1:
        index += 1
        return htmlContent[index: htmlContent.find(';', index)].strip()
    return None


def getPlayParameter(url: str, referer="https://www.88kan.tv/"):
    """
    获取请求必要加密参数
    :param url: 链接
    :param referer: 防盗链接
    :return: 加密参数
    """
    htmlContent = requests.get(url=url, headers={
        "User-Agent": USER_AGENT,
        "referer": referer
    }).text
    Host = urlparse(url=url).hostname
    Domain = find_string_val(htmlContent, 'var Domain')
    server_time = find_int_val(htmlContent, 'var Time')
    vurl = find_string_val(htmlContent, 'var Vurl')
    vkey = find_string_val(htmlContent, 'var Vkey')
    key = find_string_val(htmlContent, 'var Key')
    Sign = encodeUrl(
        lc(encodeMd5(Host + server_time + vurl + key)),
        find_string_val(htmlContent, 'var Sign', tag="'"))
    return {
        'Api': find_string_val(htmlContent, 'var Api'),
        'Host': Host,
        'Domain': Domain,
        'Url': find_string_val(htmlContent, 'var Url'),
        'Time': server_time,
        'Vurl': vurl,
        'Vkey': vkey,
        'Key': key,
        'Ref': find_string_val(htmlContent, 'var Ref'),
        'Sign': Sign,
        'Token': encodeUrl(
            lc(encodeMd5(Domain + server_time + vurl + Sign)),
            server_time + find_string_val(htmlContent, 'var Token', tag="'")
        ),
        'Version': find_string_val(htmlContent, 'var Version'),
        'Type': find_string_val(htmlContent, 'var Type'),
    }


def getPlayUrl(url: str):
    """
    获取播放链接,目前测试通过腾讯视频解析
    :param url: 示例"https://v.qq.com/x/cover/mzc0020020cyvqh/r00418ld4f2.html"
    :return: m3u8播放地址
    """
    url = f"https://v.jsjinfu.com:8443/?v=" + url
    params = getPlayParameter(url=url)
    r = requests.post(f"{params['Api']}/Api.php", headers={
        "User-Agent": USER_AGENT,
        'Token': params['Vkey'],
        'Access-Token': params['Vkey'] + '-' + params['Key'] + '-' + params['Sign'] + '-' + params['Token'],
        'Version': params['Version'],
        'referer': url
    }, data={
        'url': params['Vurl'],
        'wap': 0,
        'ios': 0,
        'host': params['Host'],
        'key': params['Key'],
        'sign': params['Sign'],
        'token': params['Token'],
        'type': params['Type'],
        'referer': params['Ref'],
        'time': params['Time']
    })
    if r.status_code == 200:
        url = r.json()['url']
        return unquote(decodeUrl(url, encodeMd5(params['Host'] + params['Token'])))
